package com.peking.donations.plugins.pay.wx.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.google.common.base.Strings;
import com.peking.donations.base.util.JaxbUtil;
import com.peking.donations.base.util.SequenceUtil;
import com.peking.donations.base.util.Signature;
import com.peking.donations.plugins.pay.wx.constants.WxAPI;
import com.peking.donations.plugins.pay.wx.protocol.query.PayQueryRepData;
import com.peking.donations.plugins.pay.wx.protocol.query.PayQueryReqData;
import com.peking.donations.plugins.pay.wx.utils.Configure;
import com.peking.donations.plugins.pay.wx.utils.WxpayException;

/**
 * PayQueryService
 * <p>
 * <p>
 * </p>
 *
 * @author Vigor Yuan
 */
@Service
public class PayQueryService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    Configure configure;

    JaxbUtil reqJaxbParser = new JaxbUtil(PayQueryReqData.class);

    JaxbUtil repJaxbParser = new JaxbUtil(PayQueryRepData.class);

    public boolean queryOrder(String transcationId) throws WxpayException {

        PayQueryReqData reqData = new PayQueryReqData();
        reqData.setAppid(configure.getAppID());
        reqData.setMch_id(configure.getMchID());
        reqData.setNonce_str(SequenceUtil.getRandomStringByLength(6));
        reqData.setOut_trade_no(transcationId);

        // 进行签名
        try {
            String sign = Signature.getSign(reqData, configure.getKey());
            reqData.setSign(sign);
        } catch (Exception e) {
            logger.error("微信签名失败", e);
            throw new WxpayException("微信签名失败", e);
        }

        // 生成xml字符串
        String xmlData;
        try {
            xmlData = reqJaxbParser.toXml(reqData, "UTF-8");
            logger.debug("微信UNIFIED_PAY_API post数据:{}", xmlData);
        } catch (Exception e) {
            logger.error("post数据生成失败", e);
            throw new WxpayException("微信post数据生成失败", e);
        }

        // 发送请求
        ResponseEntity<String> responseEntity;
        try {
            responseEntity = restTemplate.postForEntity(WxAPI.PAY_QUERY_API.getApi(), xmlData, String.class);
            logger.debug("微信post 返回数据[{}]", responseEntity);
        } catch (Exception e) {
            logger.error("微信post失败", e);
            throw new WxpayException("微信post失败", e);
        }
        PayQueryRepData repData = repJaxbParser.fromXml(responseEntity.getBody());
        if (Strings.isNullOrEmpty(repData.getReturn_code()) || !repData.getReturn_code().equals("SUCCESS")
                || Strings.isNullOrEmpty(repData.getResult_code()) || repData.getResult_code().equals("")) {
            throw new WxpayException(
                    String.format("微信查询异常,returnCode[%s],resultCode[%s]", repData.getReturn_code(), repData.getResult_code()));
        } else {
            if (repData.getTrade_state().equals("SUCCESS")) {
                return true;
            }
        }
        return false;
    }
}
